use clap::Args;
use image::imageops::FilterType;
use std::{fs, path::Path};

#[derive(Args, Debug)]
#[clap(about="图片分辨率的重置", long_about=None)]
pub(crate) struct Resize {
    #[clap(
        value_parser,
        default_value = "./input",
        help = "输入目录",
        display_order = 1
    )]
    pub input: String,
    #[clap(
        value_parser,
        default_value = "./output",
        help = "输出目录",
        display_order = 2
    )]
    pub output: String,
    #[clap(
        long,
        value_parser,
        default_value = "600",
        help = "目标图片宽度",
        display_order = 3
    )]
    pub width: u32,
    #[clap(
        long,
        value_parser,
        default_value = "400",
        help = "目标图片高度",
        display_order = 4
    )]
    pub height: u32,
}

pub(crate) fn resize(input: &str, output: &str, width: u32, height: u32) {
    let result = fs::create_dir_all(output);
    if result.is_err() {
        println!("create output dir error: {:?}", result);
        return;
    }
    let output_file = Path::new(output);
    let paths = fs::read_dir(input).unwrap();
    for path in paths {
        let f = path.unwrap();
        let fpath = f.path();
        let ext = match fpath.extension() {
            Some(p) => p.to_str().unwrap(),
            None => "",
        };
        let lcext = &ext.to_lowercase();
        if ext.len() == 0 || (lcext != "png" && lcext != "jpg") {
            continue;
        }
        let im = image::open(&fpath).unwrap();
        let newim = im.resize(width, height, FilterType::Nearest);
        let file_name = f.file_name();
        let output_file = output_file.join(file_name);
        println!("输出文件：{}", output_file.to_str().unwrap());
        newim.save(output_file).unwrap();
    }
}
